﻿using System;
using System.Collections.Generic;
using MyWpf.Common.Common;

namespace MyWpf.Common.MessageBroker
{
    public interface IContextBroker
    {
        IDisposable RegisterProvider<T>(object provider, IObservable<T> contextObservable) where T : IContext;
        IDisposable RegisterListener<T>(IObserver<T> contextObserver) where T : IContext;
    }

    public interface IContextStrategy : IContextBroker
    {
        Type ContextType { get; }
    }

    public class ContextBroker : IContextBroker
    {
        private readonly IDictionary<Type, IContextStrategy> _contextStrategies = new Dictionary<Type, IContextStrategy>();
        private IContextStrategy _defaultContextStrategy;

        public ContextBroker()
        {
            _defaultContextStrategy = new BroadcastContextStrategy();
        }

        public IDisposable RegisterProvider<T>(object provider, IObservable<T> contextObservable) where T : IContext
        {
            var typeofT = typeof(T);
            var contextStrategy = _contextStrategies.ValueOf(typeofT) ?? _defaultContextStrategy;

            return contextStrategy.RegisterProvider(provider, contextObservable);
        }

        public IDisposable RegisterListener<T>(IObserver<T> contextObserver) where T : IContext
        {
            var typeofT = typeof(T);
            var contextStrategy = _contextStrategies.ValueOf(typeofT) ?? _defaultContextStrategy;

            return contextStrategy.RegisterListener(contextObserver);
        }
    }
}
